<?php
    require_once('config.php');
    if(empty(date('YmdHis').$_FILES['upload_file']['name'])){
        $arr = array(
            'error'=>"请输入文件名",
        );
        echo json_encode($arr);
    }elseif(strpos($_FILES['upload_file']['name'],'/')){
        $arr = array(
            'error'=>"文件名中不允许存在/",
        );
        echo json_encode($arr);
    }elseif(!is_writable($_GET['saveUrl'])){
        $arr = array(
            'error'=>"该文件夹没有写权限",
        );
        echo json_encode($arr);
    }elseif(file_exists($_GET['saveUrl'].'/'.date('YmdHis').$_FILES['upload_file']['name'])){
        $arr = array(
            'error'=>"文件已存在",
        );
        echo json_encode($arr);
        exit;
    }else{
        try{
            $pdo = new PDO("mysql:host=".mysqlAddress.";dbname=".mysqlDB,mysqlUser,mysqlPassword);
            $pdo->query("set names utf8");
            $data = array();
            $res = $pdo->query("select COLUMN_NAME,column_comment from INFORMATION_SCHEMA.Columns where table_name='".mysqlTable."'");
            while($row = $res->fetch()){
                $data[] = ($row['COLUMN_NAME']);
            }
            $sql = "insert into ".mysqlTable." set";
            foreach($data as $v){
                if($v == columnSaveUrl){
                    $sql .= " `".$v."`='".$_GET['saveUrl']."',";
                }elseif($v == columnType){
                    $sql .= " `".$v."`='image',";
                }elseif($v == columnName){
                    $sql .= " `".$v."`='".date('YmdHis').$_FILES['upload_file']['name']."',";
                }elseif($v == columnAddTime){
                    $sql .= " `".$v."`=Now(),";
                }else{
                    $sql .= " `".$v."`=null,";
                }
            }
            $sql = rtrim($sql,',');
            $pdo->beginTransaction();
            $pdo->query($sql);
            $is_finish = move_uploaded_file($_FILES['upload_file']['tmp_name'],$_GET['saveUrl'].'/'.date('YmdHis').$_FILES['upload_file']['name']);
            if($is_finish){
                $pdo->commit();
                $arr = array(
                    'success'=>"成功",
                );
            }else{
                $pdo->rollBack();
                $arr = array(
                    'error'=>"缺少操作文件权限",
                );
            }
            echo json_encode($arr);
        }catch(PDOException $ex){
            $arr = array(
                'error'=>"数据库未知错误请打印sql语句排查",
            );
            $pdo->rollBack();
            echo json_encode($arr);
        }
    }
